# -*- coding: utf-8 -*-
import json

from odoo import http
from odoo.addons.weixin.api.session_manager import session_obj
import logging

_logger = logging.getLogger(__name__)

class WliotMessageController(http.Controller):
    ''' 查询所有消息 '''
    @http.route('/wliot/message/queryAllMsg', auth='public')
    def queryAllMsg(self, **kw):
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            # 查询联接消息
            dicts1 = self.query_connect_information(partner.id)
            _logger.info(dicts1)
            count = 0
            connect = {}
            if dicts1:
                for dict in dicts1:
                    if dict.get('is_read') == False:
                        count += 1
                if dicts1[0].get('name') == 'lostin':
                    message = u'这是一条失联消息'
                elif dicts1[0].get('name') == 'lostin_remove':
                    message = u'这是一条失联修复消息'
                connect = {
                    'message': message,
                    'time': dicts1[0].get('date'),
                    'count': count
                }
            # res_id = dict.get('res_id')
            # date = dict.get('date')
            # create_date = dict.get('create_date')
            # create_date = create_date[5:10]
            # device = http.request.env['wliot.device'].sudo().search([
            #     ('id', '=', res_id)
            # ], limit=1)
            # connect.append({
            #     'barcode': device.barcode,
            #     'location': device.location,
            #     'msg_time': create_date,
            #     'date': date
            # })
            # 查询预警消息
            dicts2 = self.query_warning_information(partner.id)
            _logger.info(dicts2)
            count = 0
            warning = {}
            if dicts2:
                for dict in dicts2:
                    if dict.get('is_read') == False:
                        count += 1
                if dicts2[0].get('name') == 'conc_warning':
                    message = u'这是一条浓度预警消息'
                elif dicts2[0].get('name') == 'temp_warning':
                    message = u'这是一条温度预警消息'
                warning = {
                    'message': message,
                    'time': dicts2[0].get('date'),
                    'count': count
                }
            # warning = []
            # for dict in dicts2:
            #     res_id = dict.get('res_id')
            #     create_date = dict.get('create_date')
            #     create_date = create_date[5:10]
            #     device = http.request.env['wliot.device'].sudo().search([
            #         ('id', '=', res_id)
            #     ], limit=1)
            #     warning.append({
            #         'barcode': device.barcode,
            #         'location': device.location,
            #         'msg_time': create_date,
            #     })
            # 查询更换传感器消息
            dicts3 = self.query_sensor_change_information(partner.id)
            _logger.info(dicts3)
            count = 0
            changeSensor = {}
            if dicts3:
                for dict in dicts3:
                    if dict.get('is_read') == False:
                        count += 1
                res_id = dicts3[0].get('res_id')
                sensor = http.request.env['wliot.ppm.sensor'].sudo().search([
                    ('id', '=', res_id)
                ], limit=1)
                message = u'该传感器使用寿命将于%s到期，请及时更换！' % sensor.deadline_date
                changeSensor = {
                    'message': message,
                    'time': dicts3[0].get('date'),
                    'count': count
                }
            # changeSensor = []
            # for dict in dicts3:
            #     res_id = dict.get('res_id')
            #     create_date = dict.get('create_date')
            #     create_date = create_date[5:10]
            #     sensor = http.request.env['wliot.ppm.sensor'].sudo().search([
            #         ('id', '=', res_id)
            #     ], limit=1)
            #     device = http.request.env['wliot.device'].sudo().search([
            #         ('ppm_sensor_id', '=', sensor.id)
            #     ], limit=1)
            #     changeSensor.append({
            #         'barcode': device.barcode,
            #         'sensor_no': sensor.barcode,
            #         'location': device.location,
            #         'dead_date': sensor.deadline_date,
            #         'msg_time': create_date,
            #     })
            data = {
                'connect': connect,
                'warning': warning,
                'changeSensor': changeSensor
            }
            _logger.info(data)
            return json.dumps({
                'success': True,
                'message': u'查询成功',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/message/queryMsg', auth='public')
    def queryMsg(self, **kw):
        ''' 分类查询消息 '''
        try:
            partner = self.get_partner_by_session_id(kw)
            if not partner:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': self.get_partner_by_session_id(kw)
                })
            type = kw.get('type')
            type = str(type)
            data = {}
            if not type:
                return json.dumps({
                    'success': False,
                    'message': u'参数缺失',
                    'code': 400
                })
            elif type == 'lostin':
                dicts = self.query_lostin_information(partner.id)
                lostin = []
                for dict in dicts:
                    msg_id = dict.get('id')
                    res_id = dict.get('res_id')
                    date = dict.get('date')
                    is_read = dict.get('is_read')
                    if not is_read:
                        is_read = False
                    create_date = dict.get('create_date')
                    create_date = create_date[5:10]
                    device = http.request.env['wliot.device'].sudo().search([
                        ('id', '=', res_id)
                    ], limit=1)
                    lostin.append({
                        'msg_id': msg_id,
                        'barcode': device.barcode,
                        'location': device.location,
                        'msg_time': create_date,
                        'date': date,
                        'is_read': is_read
                    })
                data = {
                    'lostin': lostin,
                }
            elif type == 'lostin_remove':
                dicts = self.query_lostin_remove_information(partner.id)
                lostin_remove = []
                for dict in dicts:
                    msg_id = dict.get('id')
                    res_id = dict.get('res_id')
                    date = dict.get('date')
                    is_read = dict.get('is_read')
                    if not is_read:
                        is_read = False
                    create_date = dict.get('create_date')
                    create_date = create_date[5:10]
                    device = http.request.env['wliot.device'].sudo().search([
                        ('id', '=', res_id)
                    ], limit=1)
                    lostin_remove.append({
                        'msg_id': msg_id,
                        'barcode': device.barcode,
                        'location': device.location,
                        'msg_time': create_date,
                        'date': date,
                        'is_read': is_read
                    })
                data = {
                    'lostin_remove': lostin_remove
                }
            elif type == 'temp_warning':
                dicts = self.query_temp_warning_information(partner.id)
                temp_warning = []
                for dict in dicts:
                    is_read = dict.get('is_read')
                    if not is_read:
                        is_read = False
                    res_id = dict.get('res_id')
                    msg_id = dict.get('id')
                    create_date = dict.get('create_date')
                    create_date = create_date[5:10]
                    device = http.request.env['wliot.device'].sudo().search([
                        ('id', '=', res_id)
                    ], limit=1)
                    temp_warning.append({
                        'msg_id': msg_id,
                        'barcode': device.barcode,
                        'location': device.location,
                        'msg_time': create_date,
                        'is_read': is_read,
                    })
                data = {
                    'temp_warning': temp_warning,
                }
            elif type == 'conc_warning':
                dicts = self.query_conc_warning_information(partner.id)
                conc_warning = []
                for dict in dicts:
                    is_read = dict.get('is_read')
                    if not is_read:
                        is_read = False
                    res_id = dict.get('res_id')
                    msg_id = dict.get('id')
                    create_date = dict.get('create_date')
                    create_date = create_date[5:10]
                    device = http.request.env['wliot.device'].sudo().search([
                        ('id', '=', res_id)
                    ], limit=1)
                    conc_warning.append({
                        'msg_id': msg_id,
                        'barcode': device.barcode,
                        'location': device.location,
                        'msg_time': create_date,
                        'is_read': is_read
                    })
                data = {
                    'conc_warning': conc_warning
                }
            elif type == 'expire':
                dicts = self.query_sensor_change_information(partner.id)
                expire = []
                for dict in dicts:
                    msg_id = dict.get('id')
                    res_id = dict.get('res_id')
                    is_read = dict.get('is_read')
                    if not is_read:
                        is_read = False
                    create_date = dict.get('create_date')
                    create_date = create_date[5:10]
                    sensor = http.request.env['wliot.ppm.sensor'].sudo().search([
                        ('id', '=', res_id)
                    ], limit=1)
                    device = http.request.env['wliot.device'].sudo().search([
                        ('ppm_sensor_id', '=', sensor.id)
                    ], limit=1)
                    expire.append({
                        'msg_id': msg_id,
                        'barcode': device.barcode,
                        'sensor_no': sensor.barcode,
                        'location': device.location,
                        'dead_date': sensor.deadline_date,
                        'msg_time': create_date,
                        'is_read': is_read,
                    })
                data = {
                    "expire": expire
                }
            return json.dumps({
                'success': True,
                'message': u'查询成功',
                'data': data
            })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'code': 500,
                    'success': False,
                    'message': error
                })

    @http.route('/wliot/message/readMsg', auth='none')
    def readMsg(self, **kw):
        partner = self.get_partner_by_session_id(kw)
        if not partner:
            return json.dumps({
                'success': False,
                'code': 500,
                'message': self.get_partner_by_session_id(kw)
            })
        msg_id = kw.get("msgId")
        sql = "update mail_message_res_partner_needaction_rel " \
              "set is_read=true " \
              "where mail_message_res_partner_needaction_rel.mail_message_id=%s " \
              "and mail_message_res_partner_needaction_rel.res_partner_id=%s" % (msg_id, partner.id)
        http.request.env.cr.execute(sql)


    # mail_message_subtype 消息类型
    # mail_message 的 model 消息指定到的模型， res_id 模型的资源id
    def query_lostin_information(self, partner_id):
        ''' 查询失联消息 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name='lostin' and c.res_partner_id=%s " \
              "order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        lostin_dicts = http.request.env.cr.dictfetchall()
        return lostin_dicts

    def query_lostin_remove_information(self, partner_id):
        ''' 查询失联解除消息 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name = 'lostin_remove' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        lostin_remove_dicts = http.request.env.cr.dictfetchall()
        return lostin_remove_dicts

    def query_temp_warning_information(self, partner_id):
        ''' 查询温度报警消息 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name = 'temp_warning' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        dicts = http.request.env.cr.dictfetchall()
        return dicts

    def query_conc_warning_information(self, partner_id):
        ''' 查询湿度报警消息 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name = 'conc_warning' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        dicts = http.request.env.cr.dictfetchall()
        return dicts

    def query_sensor_change_information(self, partner_id):
        ''' 查询传感器更换日期 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "left join mail_message_subtype b on a.subtype_id=b.id " \
              "left join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.ppm.sensor' and b.name = 'expire' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        dicts = http.request.env.cr.dictfetchall()
        return dicts

    def query_connect_information(self, partner_id):
        ''' 查询联接消息，合并失联与失联解除 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name = 'lostin' or b.name='lostin_remove' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        dicts = http.request.env.cr.dictfetchall()
        return dicts

    def query_warning_information(self, partner_id):
        ''' 查询报警消息，合并温度预警和湿度预警 '''
        sql = "select a.id,a.subject,a.date,a.create_date,a.res_id,a.model,a.subtype_id,b.name,c.res_partner_id,c.is_read " \
              "from mail_message a " \
              "inner join mail_message_subtype b on a.subtype_id=b.id " \
              "inner join mail_message_res_partner_needaction_rel c on a.id=c.mail_message_id " \
              "where a.message_type='notification' and a.model='wliot.device' and b.name = 'temp_warning' or b.name='conc_warning' " \
              "and c.res_partner_id=%s order by date desc limit 20" % partner_id
        http.request.env.cr.execute(sql)
        dicts = http.request.env.cr.dictfetchall()
        return dicts

    def get_partner_by_session_id(self, kw):
        '''检查session是否过期，并根据session_id返回该微信号可以查看的客户'''
        session_id = kw.get('SessionID')
        if not session_id:
            return {
                'success': False,
                'code': 400,
                'msg': u'请传入session_id！',
            }
        open_id = session_obj.pydis.get(session_id)
        if not open_id:
            return {
                'success': False,
                'code': 900,
                'msg': u'sessoin已过期，请重新获取！',
            }
        wechat_recs = http.request.env['weixin.user'].sudo().search([('open_id', '=', open_id)])
        partner = http.request.env['res.partner'].sudo().search([('id', '=', wechat_recs.partner_id.id)])
        return partner

    def check_phone_legal(self, phone):
        '''是否存在该电话的客户，若存在则返回该客户'''
        records = http.request.env['res.partner'].sudo().search([
            # ('partner_type', '=', 'customer'),
            ('phone', '=', phone)
        ])
        if not records:
            return {
                'success': False,
                'msg': u'不存在电话为%s的客户！' % phone,
            }
        else:
            return {
                'success': True,
                'value': records,
            }